#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <windows.h>
//函数外全局变量定义

int high, width;					//画面尺寸
int ball_x, ball_y;					//小球坐标
int ball_vx, ball_vy;				//小球速度
int position_x, position_y;		//挡板中心坐标
int radius;							//挡板半径
int left, right;					//挡板左右边界
int ball_number;					//反弹次数
int target_x, target_y;				//砖块
int score;							//得分

void gotoxy(int x, int y)
{
	HANDLE handle = GetStdHandle(STD_OUTPUT_HANDLE);
	COORD pos;
	pos.X = x;
	pos.Y = y;
	SetConsoleCursorPosition(handle, pos);
}

void HideCursor()
{
	CONSOLE_CURSOR_INFO cursor_info = { 1,0 };//第二个值为0表示隐藏光标
	SetConsoleCursorInfo(GetStdHandle(STD_OUTPUT_HANDLE), &cursor_info);
}

void startup()						//数据初始化
{
	high = 16;
	width = 25;

	ball_x = 1;
	ball_y = width / 2;

	ball_vx = 1;
	ball_vy = 1;

	position_x = high;
	position_y = width / 2;
	radius = 5;
	left = position_y - radius;
	right = position_y + radius;

	ball_number = 0;

	score = 0;
	target_x = 0;
	target_y = width / 2-1;

	HideCursor(); //隐藏光标
}

void show()    //显示画面
{
	gotoxy(0, 0);					//光标移动到原点
	int i, j;
	for (i = 0; i <= high+1; i++)
	{
		for (j = 0; j <= width; j++)
		{
			if ((i == ball_x) && (j == ball_y))
				printf("*");		//输出小球
			else if (j == width)
				printf("|");		//右边界
			else if (i == high + 1)
				printf("-");		//下边界
			else if ((i == position_x) && (j >= left) && (j <= right))
				printf("*");		//挡板
			else if (i == target_x && j == target_y)
				printf("#");		//砖块
			else
				printf(" ");		//输出空格
		}
		printf("\n");
	}
	printf("反弹小球数：%d\n",ball_number);
	printf("得分：%d\n", score);
}

void updateWithoutInput()		//与用户输入无关的更新
{
	if (ball_x == position_x-1)
	{
		if (ball_y >= left && ball_y <= right)
		{
			ball_number++;
			ball_vx = -ball_vx;
		}
	}
	if (ball_x == high-1)
	{
			printf("Game Over!");
			exit(0);
	}

	if (ball_x == target_x && ball_y == target_y)
	{
		score++;
		target_y = rand() % 25;
		target_x = rand() % 10;
	}							//击中砖块

	ball_x = ball_x + ball_vx;
	ball_y = ball_y + ball_vy;	//小球移动

	if (ball_x == 0 || ball_x == high - 1)
		ball_vx = -ball_vx;
	if (ball_y == 0 || ball_y == width - 1)
		ball_vy = -ball_vy;		//边界反弹

	Sleep(100);

}
void updateWithInput()			//与用户输入有关的更新
{
	int i = 1;
	char input;
	if (kbhit())		//当按键时执行
	{
		input = getch();
		if (input == 'a')
		{
			position_y=position_y-2;
			left = position_y - radius;
			right = position_y + radius;
		}
		if (input == 'd')
		{
			position_y=position_y+2;
			left = position_y - radius;
			right = position_y + radius;
		}
		if (input == 'w')
		{
			position_x--;
		}
		if(input=='s')
		{
			position_x++;
		}
	}
}

int main()
{
	startup();
	while (1)
	{
		show();					//显示画面
		updateWithoutInput();	//与用户输入无关的更新
		updateWithInput();		//与用户输入有关的更新
	}
	return 0;
}